package com.sky.Screen;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.healthcare.widget.ActionBar;
import com.healthcare.widget.ActionBar.IntentAction;
import com.sky.constanst.Definition;
import com.sky.heathcare.R;
import com.sky.network.DetectorNetwork;
import com.sky.restfull.WebServicesTask;



public class loginActivity extends Activity {

	EditText m_user_txt;
	EditText m_pass_txt;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_activity);
		
		final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);       
        actionBar.setTitle("Home");

        actionBar.setHomeAction(new IntentAction(this, MainActivity.createIntent(this), R.drawable.ic_title_home_default));
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.addAction(new IntentAction(this, createShareIntent(), R.drawable.ic_title_share_default));       
        
        /*
        final Action shareAction = new IntentAction(this, createShareIntent(), R.drawable.ic_title_share_default);
        actionBar.addAction(shareAction);
        final Action otherAction = new IntentAction(this, new Intent(this, OtherActivity.class), R.drawable.ic_title_export_default);
        actionBar.addAction(otherAction);
        */
		m_user_txt = (EditText)findViewById(R.id.userTxt);
		m_pass_txt = (EditText)findViewById(R.id.passwordTxt);
		
		Button loginBtn = (Button) findViewById(R.id.login_btn);	
		loginBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Check the login
				if(login())
				{
					//Check update location
					if(checkupdateLocationFromServer())
					{
						//Update client database
					}
					else
					{
						//get last session
						if(getLastssion() == -1)
						{
							gotoLocationScreen();
						}
						else
						{
							gotoMainScreen();
						}
					}
					
				}
				else
				{
					showError();
				}

			}
		});
		
		Button exitBtn = (Button) findViewById(R.id.exit_btn);
		exitBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {			
				finish();

			}
		});
		
	}

	private void gotoMainScreen() {
		Intent intent = new Intent(this, MainActivity.class);
		intent.putExtra("USER_STATUS", true);
		intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(intent);
		
		finish();
	}
	
	private Intent createShareIntent() {
        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "Shared from the ActionBar widget.");
        return Intent.createChooser(intent, "Share");
    }
	
	private void gotoLocationScreen() {
		Intent intent = new Intent(this, SelectLocationActivity.class);	
		startActivity(intent);
		
		finish();
	}
	
	
	
	 public boolean isNetworkAvailable()
	    {
	        ConnectivityManager conMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
	        NetworkInfo i = conMgr.getActiveNetworkInfo();
	        if (i == null)
	        {
	            return false;
	        }
	        if (!i.isConnected())
	        {
	            return false;
	        }
	        if (!i.isAvailable())
	        {
	            return false;
	        }
	        return true;
	    }
	 
	/**
	 * @return : Checking login
	 */
	boolean login()
	{
		
		if(isNetworkAvailable())
		{
			System.out.println("abc");
		}
		String sUser = m_user_txt.getText().toString();
		String sPsw = m_pass_txt.getText().toString();
		
		//Login with server for testing
		
		WebServicesTask.bNotReponse = false;
    	WebServicesTask.sData = "";	
    	String urlRequest = Definition.SERVICE_URL; 
    	WebServicesTask wst = new WebServicesTask(WebServicesTask.GET_TASK, this, Definition.TITLE_LOADING);
    	wst.setLoading(true);
    	wst.execute(new String[] {urlRequest});
    	Thread getdataThread = new Thread() {					
			@Override
			public void run() {
				try {
					
					while ( WebServicesTask.sData == "" ) {
						
						sleep(100);				
						if(WebServicesTask.bNotReponse == true)
						{		
															
						}
						
					}
				} catch (InterruptedException e) {
					// do nothing
				} finally {
					
					try {
						JSONArray jsonArray = new JSONArray(WebServicesTask.sData);								
						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject jsonObject = jsonArray.getJSONObject(i);

							
						}					
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		};
		getdataThread.start();
		if(sUser.equalsIgnoreCase("admin")  && sPsw.equalsIgnoreCase("abc"))
		{
			return true;
		}
		return false;
	}
	
	
	void showError()
	{
		Context context = getApplicationContext();
		CharSequence text = "User or password not correct";
		int duration = Toast.LENGTH_SHORT;

		Toast toast = Toast.makeText(context, text, duration);
		toast.show();
	}
	
	boolean checkupdateLocationFromServer()
	{
		return false;
	}
	
	/**
	 * @return -1: need selection location
	 * Using id location to go to main activity
	 */
	int getLastssion()
	{
		return -1;
	}
	
}
